<?php
	$page = $_GET['page'];
	
	switch($page){
		default:
			home();
			break;
		case "request_account":
			request_account();
			break;
		case "forgot_password":
			forgot_password();
			break;
		case "logout":
			logout();
			break;
		case "my_account":
			validating_authentication();
			my_account();
			break;
		case "cmfs":
			validating_authentication();
			cmfs();
			break;
		case "manager_user":
			validating_authentication('admin');
			manager_user();
			break;
		case "edit_user":
			validating_authentication('admin');
			edit_user();
			break;
		case "pendency":
			validating_authentication('admin');
			pendency();
			break;
	}
		
	function home(){
		echo "<div id='text'>
				<a class='title'>FIBRE Testbed Access</a>
				<a>Welcome to the main access to FIBRE Testbed.</a>
				
				<a>This page gives access to a remote experimental infrastructure (or testbed) for tests with computer networks and distributed systems.</a>
				
				<a>The main goal of the FIBRE project is the design, implementation and validation of a shared Future Internet research facility, supporting the joint experimentation of European and Brazilian researchers. In order to achieve this goal the project will carry out four main activities:</a>
				<a>• The development and operation of a new experimental facility in Brazil, including the setup of equipment to support experimentation with various technologies (fixed layer 2 and layer 3, wireless, optical) as well as the design and implementation of a control framework to automate the use and operation of the testbed.</a>
				<a>• The development and operation of a Future Internet facility in Europe based on enhancements and the federation of two existing infrastructures: OFELIA and OneLab. Two OFELIA islands (i2CAT and UEssex) and the UTH's NITOS testbed will be enhanced by i) adding more physical resources (servers, OpenFlow-enabled switches and access points) to be able to cope with a bigger number of users and different use cases, ii) improving its respective control frameworks (based on the OFELIA control framework and OMF) and iii) adding more manpower to operate the facilities.</a>
				<a>• The federation of the Brazilian and European experimental facilities, both at the physical connectivity and control framework level, to support the provisioning of slices using resources from both testbeds.</a>
				<a>• The design and implementation of pilot applications of public utility that showcase the power of a shared Europe-Brazil Future Internet experimental facility.</a>
			</div>
		";
	}
	
	function cmfs(){
		echo "<div id='text'>
				<a class='title'>Welcome ".$_SESSION[''.SECURITY_SESSION.'']['username']."</a>
     		  </div>
     		  <div><center>Resource Reservation</center></div>
     		  <div class='button'>
				<a href='../NS-BR'>OMF</a>
				<a href='https://200.130.15.177/'>OCF</a>
				<a href='https://www.emulab.larc.usp.br/'>ProtoGENI</a>
     		  </div>
     		  
     		  <div style='text-align: justify; margin: 10px 20px;'>FIBRE Portal is under construction and for while ProtoGENI is not federated yet. So, by choosing ProtoGENI, you will be redirected to a different site with a new Web session. Besides, you will need to create another account.</div>
		";
	}
	
	function my_account(){
		$ldap_connection = ldap_connect(HOST_LDAP,PORT_LDAP) or die("Error connecting to the LDAP server");
				
		ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
		ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
		
		if(isset($_POST['sbmt'])){
			$username = $_POST['username'];
			$name = $_POST['name'];
			$email = $_POST['email'];
			$current_password = $_POST['current_password'];
			$password = $_POST['password'];
			$password2 = $_POST['password2'];
			
			if(empty($username) || empty($name) || empty($email))
				set_message('Fill out all fields to continue.','alert',1);
			else{
				$institution = "".substr($username, strpos($username, "@")+1)."";
				$organization = "o=".substr($username, strpos($username, "@")+1)."";
				$organization = str_replace(".br","",$organization);
				
				require("mysql_connection.php");
				$ldap_server = mysql_query("SELECT `ldap_ip_address` FROM ".DB_SCHEDULER.".`islands` WHERE `institution` = '".$institution."'") or print_r(mysql_error());
				$ldap_server = mysql_fetch_object($ldap_server);
				
				$ldap_connection_island = ldap_connect($ldap_server->ldap_ip_address,PORT_LDAP) or die("Error connecting to the LDAP server of island");
				
				ldap_set_option($ldap_connection_island, LDAP_OPT_PROTOCOL_VERSION, 3);
				ldap_set_option($ldap_connection_island, LDAP_OPT_REFERRALS, 0);
				
				$ldap_bind = ldap_bind($ldap_connection_island, ISLAND_USER_LDAP, ISLAND_PASS_LDAP);

				$change = array(
							"sn" => array($name),
							"mail" => array($email)
						  );
						  
				// Change password:
				if(!empty($password) && !empty($password2) && ($password != $password2)){
					set_message('Passwords do not match.','alert',1);
					$password_error = TRUE;
				}else if(!empty($current_password) && !empty($password) && !empty($password2)){
					// search my current password
					$search_for = 'uid='.$username.'';		
					$search = ldap_search($ldap_connection, "".$_SESSION[''.SECURITY_SESSION.'']['organization'].",".LDAP_TREE."", $search_for);
					$ldapResults = ldap_get_entries($ldap_connection, $search);
					
					$current_password = '{CRYPT}'.md5crypt($current_password, substr($ldapResults[0]['userpassword'][0],7,12)).'';
					$password_verify = ldap_compare($ldap_connection, "uid=".$username.",".LDAP_PEOPLE.",".$_SESSION[''.SECURITY_SESSION.'']['organization'].",".LDAP_TREE."", 'userpassword', $current_password);
					
					if($password_verify == 1){
						$password = '{CRYPT}'.md5crypt($password).'';
						$change['userpassword'] = array($password);
					}else{
						set_message('Wrong current password.','error',1);
						$password_error = TRUE;
					}
				}

				if(!isset($password_error)){
					$modify = ldap_modify($ldap_connection_island, "uid=".$username.",".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."", $change);
					
					if($modify)
						set_message('User edited successfully!','success',1);
					else
						set_message('Error to edit this user, try again.','error',1);
				}
			}
		}
		
		// Recover my account data
		$search_for = 'uid='.$_SESSION[''.SECURITY_SESSION.'']['username'].'';		
		$search = ldap_search($ldap_connection, "".$_SESSION[''.SECURITY_SESSION.'']['organization'].",".LDAP_TREE."", $search_for);  
		
		$ldapResults = ldap_get_entries($ldap_connection, $search);
		if($ldapResults['count'] < 1)
			Header("Location: index.php?page=logout");
		
		// Define form default values
		$username = ($ldapResults[0]['uid'][0] != $_POST['username'] && isset($_POST['username'])) ? $_POST['username'] : $ldapResults[0]['uid'][0];
		$name = ($ldapResults[0]['sn'][0] != $_POST['name'] && isset($_POST['name'])) ? $_POST['name'] : $ldapResults[0]['sn'][0];
		$email = ($ldapResults[0]['mail'][0] != $_POST['email'] && isset($_POST['email'])) ? $_POST['email'] : $ldapResults[0]['mail'][0];
		
		echo "<div id='text'>
				<a class='title'>My Account: ".$_SESSION[''.SECURITY_SESSION.'']['username']."</a>
			  </div>";
		
		echo "<form method='POST' action='' id='registration'>
				<table>
					<tr>
						<td>Login Name</td>
						<td><input type='text' name='username' value='".$username."' readonly/></td>
					</tr>
					
					<tr>
						<td>Full Name</td>
						<td><input type='text' name='name' value='".$name."'/></td>
					</tr>
					
					<tr>
						<td>E-mail</td>
						<td><input type='text' name='email' value='".$email."'/></td>
					</tr>
					
					<tr>
						<td>Current password</td>
						<td><input type='password' name='current_password'/></td>
					</tr>
					
					<tr>
						<td>New password</td>
						<td><input type='password' name='password'/></td>
					</tr>
					
					<tr>
						<td>Re-type password</td>
						<td><input type='password' name='password2'/></td>
					</tr>

					<tr>
						<td></td>
						<td><input type='submit' value='Apply changes' name='sbmt'/></td>
					</tr>
				</table>
			</form>";
	}
	
	function request_account(){
		require("mysql_connection.php");
		
		if(isset($_POST['sbmt'])){
			$username = $_POST['username'];
			$password = $_POST['password'];
			$password2 = $_POST['password2'];
			$name = $_POST['name'];
			$email = $_POST['email'];
			$institution = $_POST['institution'];
			
			if(empty($username) || empty($password) || empty($password2) || empty($name) || empty($institution))
				set_message('Fill out all fields to continue.','alert',1);
			else if($password != $password2)
				set_message('Passwords do not match.','alert',1);
			else{
				$ldap_server = mysql_query("SELECT `ldap_ip_address` FROM ".DB_SCHEDULER.".`islands` WHERE `institution` = '".$institution."'") or print_r(mysql_error());
				$ldap_server = mysql_fetch_object($ldap_server);
				
				$ldap_connection = ldap_connect($ldap_server->ldap_ip_address,PORT_LDAP) or die("Error connecting to the LDAP server");
				
				ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
				ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
				
				if ($ldap_connection) {
					$search_for = 'uid='.$username.'@'.$institution.'';
					
					$organization = "o=".$institution."";
					$organization = str_replace(".br","",$organization);
					
					$ldap_bind = ldap_bind($ldap_connection, ISLAND_USER_LDAP, ISLAND_PASS_LDAP);
					
					$search = ldap_search($ldap_connection, "".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."", $search_for);  

					if(ldap_count_entries($ldap_connection, $search)){
						set_message('There is already a registered user with this Login Name.','error',1);
					}else{
						$search_max_uid = ldap_search($ldap_connection, "".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."", "uid=*");  
						$ldapResults = ldap_get_entries($ldap_connection, $search_max_uid);
						
						$max_uidn = 0;
						for ($item = 0; $item < $ldapResults['count']; $item++) {
							if($ldapResults[$item]['uidnumber'][0] > $max_uidn) $max_uidn = $ldapResults[$item]['uidnumber'][0];
						}
						
						if($max_uidn < 1500) $max_uidn = 1501; else $max_uidn++;
						
						$password = '{CRYPT}'.md5crypt($password).'';
						
						// Search group id:
						$search_group = ldap_search($ldap_connection, "".LDAP_GROUP.",".$organization.",".LDAP_TREE."", "cn=".$institution."");  
						$group_results = ldap_get_entries($ldap_connection, $search_group);
						
						$group_id = $group_results[0]['gidnumber'][0];
						
						// Creating user
						$data = array('cn' => $username,
									  'gidnumber' => $group_id,
									  'homedirectory' => '/home/'.$institution.'/'.$username.'',
									  'objectClass' => array('top','person','inetOrgPerson','posixAccount','eduPerson','brPerson','schacPersonalCharacteristics','fibre'),
									  'sn' => $name,
									  'uidnumber' => $max_uidn,
									  'uid' => ''.$username.'@'.$institution.'',
									  'eduPersonPrincipalName' => ''.$username.'@'.$institution.'',
									  'mail' => $email,
									  'userpassword' => ''.$password.'',
									  'loginShell' => '/bin/bash',
									  'userEnable' => 'FALSE',
									  'omfAdmin' => 'FALSE');
									  
						$add_user = ldap_add($ldap_connection, "uid=".$data["uid"].",".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."", $data);
						
						if($add_user){
							// Send email to administrators
							$search_admin = ldap_search($ldap_connection, "".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."", "omfadmin=TRUE"); 
							$admin_results = ldap_get_entries($ldap_connection, $search_admin);
							
							$subject = 'Testbed user registration';
							$message = 'You have a new user to be evaluated in the testbed:<br><br>';
							$message .= '<b>Name:</b> '.$name.'<br>';
							$message .= '<b>E-mail:</b> '.$email.'<br>';
							$message .= '<b>Institution:</b> '.$institution.'';
							
							$sender = array('email' => $email, 'name' => $name);
							
							$receiver = array();
							for ($i = 0; $i < $admin_results['count']; $i++) {
								$receiver[] = array('email' => $admin_results[$i]['mail'][0],
													'name' => $admin_results[$i]['sn'][0]);
							}

							if(count($receiver) > 0)
								send_mail($sender, $receiver, $subject, $message);
						}else
							set_message('Error in the Registration Request, try again.','error',1);
					}
				}
			}
		}
		
		$query = mysql_query("SELECT * FROM ".DB_SCHEDULER.".`islands` ORDER BY `institution` ASC");
		
		echo "<div id='text'>
				<a class='title'>Request Account</a>
			  </div>";
		
		if($add_user){
			set_message('Request Registration was successful, wait for the approval of registration by administrators.','success',1);
		}else{
			echo "<form method='POST' action='' id='registration'>
					<table>
						<tr>
							<td>Login Name</td>
							<td><input type='text' name='username' value='".$username."'/></td>
						</tr>
						
						<tr>
							<td>Full Name</td>
							<td><input type='text' name='name' value='".$name."'/></td>
						</tr>
						
						<tr>
							<td>E-mail</td>
							<td><input type='text' name='email' value='".$email."'/></td>
						</tr>
						
						<tr>
							<td>Institution</td>
							<td>
								<select name='institution'>
									<option value=''>[Select Institution]</option>
								";
									while($resultado = mysql_fetch_object($query)){
										if($institution == $resultado->institution)
											echo '<option value="'.$resultado->institution.'" selected>('.strtoupper($resultado->institution).') '.utf8_encode($resultado->name).'</option>';
										else
											echo '<option value="'.$resultado->institution.'">('.strtoupper($resultado->institution).') '.utf8_encode($resultado->name).'</option>';
									}
								echo "
								</select>
							</td>
						</tr>
						
						<tr>
							<td>Password</td>
							<td><input type='password' name='password'/></td>
						</tr>
						<tr>
							<td>Re-type Password</td>
							<td><input type='password' name='password2'/></td>
						</tr>
						<tr>
							<td></td>
							<td><input type='submit' value='Request Account' name='sbmt'/></td>
						</tr>
					</table>
				</form>";
		}
	}
	
	
	function manager_user(){
		$ldap_connection = ldap_connect(HOST_LDAP,PORT_LDAP) or die("Error connecting to the LDAP server");
		
		ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
		ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
		
		// Remove entryes
		if(isset($_POST['remove'])){
			$institution = "".substr($_POST['remove_uid'], strpos($_POST['remove_uid'], "@")+1)."";
			$organization = "o=".substr($_POST['remove_uid'], strpos($_POST['remove_uid'], "@")+1)."";
			$organization = str_replace(".br","",$organization);
			
			require("mysql_connection.php");
			$ldap_server = mysql_query("SELECT `ldap_ip_address` FROM ".DB_SCHEDULER.".`islands` WHERE `institution` = '".$institution."'") or print_r(mysql_error());
			$ldap_server = mysql_fetch_object($ldap_server);
			
			$ldap_connection_island = ldap_connect($ldap_server->ldap_ip_address,PORT_LDAP) or die("Error connecting to the LDAP server of island");
			
			ldap_set_option($ldap_connection_island, LDAP_OPT_PROTOCOL_VERSION, 3);
			ldap_set_option($ldap_connection_island, LDAP_OPT_REFERRALS, 0);
			
			$ldap_bind = ldap_bind($ldap_connection_island, ISLAND_USER_LDAP, ISLAND_PASS_LDAP);
			$user_to_remove = "uid=".$_POST['remove_uid'].",".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."";
			
			if (ldap_delete($ldap_connection_island, $user_to_remove))
				set_message('User removed successfully!','success',1);
			else
				set_message('Error to remove this user, try again.','error',1);
		}
		
		// Search users
		if ($ldap_connection) {
			$search_for = "uid=*";
			$ldap_bind = ldap_bind($ldap_connection, USER_LDAP, PASS_LDAP);
			
			$search = ldap_search($ldap_connection, "".$_SESSION[''.SECURITY_SESSION.'']['organization'].",".LDAP_TREE."", $search_for);
			$ldapResults = ldap_get_entries($ldap_connection, $search);
		}
		
		echo "<div id='text'>
				<a class='title'>Manager users</a>
			</div>";
			
		echo "<table id='reserve' class='table_max'>
				<tr class='top'>
					<td>Username</td>
					<td>Name</td>
					<td>Email</td>
					<td width='120px'>Actions</td>
				</tr>";
		
		for ($item = 0; $item < $ldapResults['count']; $item++) {
			echo "<tr>
				<td>".$ldapResults[$item]['uid'][0]."</td>
				<td>".$ldapResults[$item]['sn'][0]."</td>
				<td>".$ldapResults[$item]['mail'][0]."</td>
				<td>
					<form action='' method='GET' style='display: inline;'>
						<input type='submit' value='Edit'>
						<input type='hidden' name='page' value='edit_user'>
						<input type='hidden' name='user_id' value='".$ldapResults[$item]['uid'][0]."'>
					</form>
					<form action='' method='POST' style='display: inline;'>
						<input type='submit' name='remove' value='Remove'>
						<input type='hidden' name='remove_uid' value='".$ldapResults[$item]['uid'][0]."'>
					</form>
				</td>
			</tr>";
			;            
		}
		echo "</table>";
	}
	
	function edit_user(){
		$ldap_connection = ldap_connect(HOST_LDAP,PORT_LDAP) or die("Error connecting to the LDAP server");
				
		ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
		ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
		
		if(isset($_POST['sbmt'])){
			$username = $_POST['username'];
			$name = $_POST['name'];
			$email = $_POST['email'];
			$password = $_POST['password'];
			$userenable = $_POST['omfenable'];
			$omfadmin = $_POST['omfadmin'];
			
			if(empty($username) || empty($name) || empty($email))
				set_message('Fill out all fields to continue.','alert',1);
			else{
				$institution = "".substr($username, strpos($username, "@")+1)."";
				$organization = "o=".substr($username, strpos($username, "@")+1)."";
				$organization = str_replace(".br","",$organization);
				
				require("mysql_connection.php");
				$ldap_server = mysql_query("SELECT `ldap_ip_address` FROM ".DB_SCHEDULER.".`islands` WHERE `institution` = '".$institution."'") or print_r(mysql_error());
				$ldap_server = mysql_fetch_object($ldap_server);
				
				$ldap_connection_island = ldap_connect($ldap_server->ldap_ip_address,PORT_LDAP) or die("Error connecting to the LDAP server of island");
				
				ldap_set_option($ldap_connection_island, LDAP_OPT_PROTOCOL_VERSION, 3);
				ldap_set_option($ldap_connection_island, LDAP_OPT_REFERRALS, 0);
				
				$ldap_bind = ldap_bind($ldap_connection_island, ISLAND_USER_LDAP, ISLAND_PASS_LDAP);

				$change = array(
							"sn" => array($name),
							"mail" => array($email),
							"userenable" => array($userenable),
							"omfadmin" => array($omfadmin)
						  );
						  
				// Change password:
				if(!empty($password)){
					$password = '{CRYPT}'.md5crypt($password).'';
					$change['userpassword'] = array($password);
				}

				$modify = ldap_modify($ldap_connection_island, "uid=".$username.",".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."", $change);
				
				if($modify)
					set_message('User edited successfully!','success',1);
				else
					set_message('Error to edit this user, try again.','error',1);
			}
		}
						
		if ($ldap_connection && isset($_GET['user_id'])) {
			$search_for = 'uid='.$_GET['user_id'].'';
			$ldap_bind = ldap_bind($ldap_connection, USER_LDAP, PASS_LDAP);
					
			$search = ldap_search($ldap_connection, "".$_SESSION[''.SECURITY_SESSION.'']['organization'].",".LDAP_TREE."", $search_for);  
		
			$ldapResults = ldap_get_entries($ldap_connection, $search);
			
			if($ldapResults['count'] < 1)
				Header("Location: index.php");
		}else
			Header("Location: index.php");
			
		$username = ($ldapResults[0]['uid'][0] != $_POST['username'] && isset($_POST['username'])) ? $_POST['username'] : $ldapResults[0]['uid'][0];
		$name = ($ldapResults[0]['sn'][0] != $_POST['name'] && isset($_POST['name'])) ? $_POST['name'] : $ldapResults[0]['sn'][0];
		$email = ($ldapResults[0]['mail'][0] != $_POST['email'] && isset($_POST['email'])) ? $_POST['email'] : $ldapResults[0]['mail'][0];
		
		echo "<div id='text'>
				<a class='title'>Edit Account - ".$username."</a>
			  </div>";
		
		echo "<form method='POST' action='' id='registration'>
				<table>
					<tr>
						<td>Login Name</td>
						<td><input type='text' name='username' value='".$username."' readonly/></td>
					</tr>
					
					<tr>
						<td>Full Name</td>
						<td><input type='text' name='name' value='".$name."'/></td>
					</tr>
					
					<tr>
						<td>E-mail</td>
						<td><input type='text' name='email' value='".$email."'/></td>
					</tr>
					
					<tr>
						<td>Password</td>
						<td><input type='password' name='password'/></td>
					</tr>
					
					<tr>
						<td>OMF Enable</td>
						<td>
							<select name='omfenable'>";
								if($ldapResults[0]['userenable'][0] == 'TRUE'){
									echo "<option value='TRUE'>Yes</option>
									<option value='FALSE'>No</option>";
								}else{
									echo "<option value='FALSE'>No</option>
									<option value='TRUE'>Yes</option>";
								}
					echo "  </select>
						</td>
					</tr>
					<tr>
						<td>Permission</td>
						<td>
							<select name='omfadmin'>";
								if($ldapResults[0]['omfadmin'][0] == 'TRUE'){
									echo "<option value='TRUE'>Administrator</option>
									<option value='FALSE'>User</option>";
								}else{
									echo "<option value='FALSE'>User</option>
									<option value='TRUE'>Administrator</option>";
								}
					echo "  </select>
						</td>
					</tr>
					<tr>
						<td></td>
						<td><input type='submit' value='Apply changes' name='sbmt'/></td>
					</tr>
				</table>
			</form>";
	}
	
	function pendency(){
		$ldap_connection = ldap_connect(HOST_LDAP,PORT_LDAP) or die("Error connecting to the LDAP server");
		
		ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
		ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
		
		// Approve / Refuse users
		if(isset($_POST['action'])){
			$username = $_POST['user_uid'];
			$institution = "".substr($username, strpos($username, "@")+1)."";
			$organization = "o=".substr($username, strpos($username, "@")+1)."";
			$organization = str_replace(".br","",$organization);
				
			require("mysql_connection.php");
			$ldap_server = mysql_query("SELECT `ldap_ip_address` FROM ".DB_SCHEDULER.".`islands` WHERE `institution` = '".$institution."'") or print_r(mysql_error());
			$ldap_server = mysql_fetch_object($ldap_server);
				
			$ldap_connection_island = ldap_connect($ldap_server->ldap_ip_address,PORT_LDAP) or die("Error connecting to the LDAP server of island");
				
			ldap_set_option($ldap_connection_island, LDAP_OPT_PROTOCOL_VERSION, 3);
			ldap_set_option($ldap_connection_island, LDAP_OPT_REFERRALS, 0);
				
			$ldap_bind = ldap_bind($ldap_connection_island, ISLAND_USER_LDAP, ISLAND_PASS_LDAP);
			
			if($_POST['action'] == 'Accept'){
				$change = array("userenable" => array('TRUE'));
				
				$search_user = ldap_search($ldap_connection, "".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."", "uid=".$username.""); 
				$user_results = ldap_get_entries($ldap_connection, $search_user);

				$modify = ldap_modify($ldap_connection_island, "uid=".$username.",".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."", $change);
				
				if($modify){							
					$subject = 'Testbed user registration';
					$message = 'Your account request has been <b>approved</b>!';
						
					set_message('User approved successfully!','success',1);
				}else
					set_message('Error to approve this user, try again.','error',1);
			}else if($_POST['action'] == 'Refuse'){
				$user_to_remove = "uid=".$username.",".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."";
				
				$search_user = ldap_search($ldap_connection, "".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."", "uid=".$username.""); 
				$user_results = ldap_get_entries($ldap_connection, $search_user);

				$remove = ldap_delete($ldap_connection_island, $user_to_remove);
	
				if ($remove){
					$subject = 'Testbed user registration';
					$message = 'Your account request has been <b>reproved</b></b><br>contact your testbed administrator';
					
					set_message('User refused successfully!','success',1);
				}else
					set_message('Error to refuse this user, try again.','error',1);
			}
			
			// Send e-mail to the user informing the approval of registration
			if($remove || $modify){
				$search_admin = ldap_search($ldap_connection, "".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."", "uid=".$_SESSION[''.SECURITY_SESSION.'']['username'].""); 
				$admin_results = ldap_get_entries($ldap_connection, $search_admin);
				
				$receiver[0] = array('email' => $user_results[0]['mail'][0],
								'name' => $user_results[0]['sn'][0]);
							
				$sender = array('email' => $admin_results[0]['mail'][0],
								  'name' => $admin_results[0]['sn'][0]);
								  
				send_mail($sender, $receiver, $subject, $message);
			}
		}
		
		// Search users
		if ($ldap_connection) {
			$search_for = "userenable=FALSE";
		
			$ldap_bind = ldap_bind($ldap_connection, USER_LDAP, PASS_LDAP);
			
			$search = ldap_search($ldap_connection, "".$_SESSION[''.SECURITY_SESSION.'']['organization'].",".LDAP_TREE."", $search_for); 
			$ldapResults = ldap_get_entries($ldap_connection, $search);
		}
		
		echo "<div id='text'>
				<a class='title'>Users pending to approve</a>
			</div>";
			
		echo "<table id='reserve' class='table_max'>
				<tr class='top'>
					<td>Username</td>
					<td>Name</td>
					<td>Email</td>
					<td width='125px'>Actions</td>
				</tr>";
				
		if($ldapResults['count'] <= 0){
			echo "<tr>
				<td colspan='4'>You have no users to evaluate.</td>
			</tr>";
		}
		
		for ($item = 0; $item < $ldapResults['count']; $item++) {
			echo "<tr>
				<td>".$ldapResults[$item]['uid'][0]."</td>
				<td>".$ldapResults[$item]['sn'][0]."</td>
				<td>".$ldapResults[$item]['mail'][0]."</td>
				<td>
					<form action='' method='POST' style='display: inline;'>
						<input type='submit' name='action' value='Accept'>
						<input type='hidden' name='user_uid' value='".$ldapResults[$item]['uid'][0]."'>
					</form>
					<form action='' method='POST' style='display: inline;'>
						<input type='submit' name='action' value='Refuse'>
						<input type='hidden' name='user_uid' value='".$ldapResults[$item]['uid'][0]."'>
					</form>
				</td>
			</tr>";           
		}
		echo "</table>";
	}
	
	function forgot_password(){
		require("mysql_connection.php");
		if(isset($_POST['sbmt'])){
			$username = $_POST['username'];
			$institution = $_POST['institution'];

			if(!strstr($username,"@".$institution."")){
				$username = "".$username."@".$institution."";
				$organization = "o=".$institution."";
			}else{
				$institution = substr($username, strpos($username, "@")+1);
				$organization = "o=".substr($username, strpos($username, "@")+1)."";
			}
			
			$organization = str_replace(".br","",$organization);

			$ldap_connection = ldap_connect(HOST_LDAP,PORT_LDAP) or die("Error connecting to the LDAP server");
			
			ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
			ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
			
			$search_for = "uid=".$username."";	
			$search = ldap_search($ldap_connection, "".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."", $search_for); 
				
			if(ldap_count_entries($ldap_connection, $search)){
				$ldapResults = ldap_get_entries($ldap_connection, $search);
				
				$ldap_server = mysql_query("SELECT `ldap_ip_address` FROM ".DB_SCHEDULER.".`islands` WHERE `institution` = '".$institution."'") or print_r(mysql_error());
				$ldap_server = mysql_fetch_object($ldap_server);
					
				$ldap_connection_island = ldap_connect($ldap_server->ldap_ip_address,PORT_LDAP) or die("Error connecting to the LDAP server of island");
					
				ldap_set_option($ldap_connection_island, LDAP_OPT_PROTOCOL_VERSION, 3);
				ldap_set_option($ldap_connection_island, LDAP_OPT_REFERRALS, 0);
					
				$ldap_bind = ldap_bind($ldap_connection_island, ISLAND_USER_LDAP, ISLAND_PASS_LDAP);
				
				// Generate a new password and change it
				$new_password = substr(md5(uniqid(time(), true)), 0, 12);
				$crypted_password = '{CRYPT}'.md5crypt($new_password).'';
				$change['userpassword'] = array($crypted_password);

				$modify = ldap_modify($ldap_connection_island, "uid=".$username.",".LDAP_PEOPLE.",".$organization.",".LDAP_TREE."", $change);
				
				if($modify){
					// Send e-mail to the user
					$subject = 'Testbed password recovery';
					$message = 'You requested a password recovery in testbed.<br>'.
							   'New password: <b>'.$new_password.'</b>';
					
					$receiver[0] = array('email' => $ldapResults[0]['mail'][0],
										 'name' => $ldapResults[0]['sn'][0]);
									
					$sender = array('email' => $ldapResults[0]['mail'][0],
									'name' => $ldapResults[0]['sn'][0]);
										  
					send_mail($sender, $receiver, $subject, $message);
					set_message('Password changed successfully, please check your email to learn your new password','success',1);
				}else
					set_message('An error occurred, please try again','error',1);
			}else
				set_message('User not found.','error',1);	
		}
		
		$query = mysql_query("SELECT * FROM ".DB_SCHEDULER.".`islands` ORDER BY `institution` ASC");
		
		echo "<div id='text'>
				<a class='title'>Recover a forgotten password</a>
			  </div>";
		
		echo "<form method='POST' action='' id='registration'>
				<table>
					<tr>
						<td>Login Name</td>
						<td><input type='text' name='username'/></td>
					</tr>
					<tr>
						<td>Institution</td>
						<td>
							<select name='institution'>
								<option value='' selected>[Select Institution]</option>
							";
								while($resultado = mysql_fetch_object($query)){
									echo '<option value="'.$resultado->institution.'">('.strtoupper($resultado->institution).') '.utf8_encode($resultado->name).'</option>';
								}
							echo "
							</select>
						</td>
					</tr>
					<tr>
						<td></td>
						<td><input type='submit' value='Recover' name='sbmt'/></td>
					</tr>
				</table>
			</form>";
	}
	
	function logout(){
		session_unset();
		header("Location: index.php");
	}
?>
